﻿using MediatR;
using PublicCommon;
using T_Rbac.Read.APi.Application.Command.MenuesCommand;
using T_Rbac_Demain;
using T_Rbac_Rep.Interface;

namespace T_Rbac.Read.APi.Application.Handlers.MenuesHandlers
{
    public class MenuesSearchByPidHandlers : IRequestHandler<MenuesSearchByPidCommand, List<PublicTree<Menues>>>
    {
        private readonly IMenues menues;

        public MenuesSearchByPidHandlers(IMenues menues)
        {
            this.menues = menues;
        }

        public async Task<List<PublicTree<Menues>>> Handle(MenuesSearchByPidCommand request, CancellationToken cancellationToken)
        {
            var list = await menues.GetvaluesByResult(x => x.Mpid == request.pid && !x.IsDel);
            var treelists = new List<PublicTree<Menues>>();
            foreach (var item in list.ToArray())
            {
                var tree = new PublicTree<Menues>
                {
                    label = item.Mname,
                    route = item.Mroute,
                    level = item.Mid,
                    pid=item.Mpid,
                    children = null
                };
                treelists.Add(tree);
                await Getchidren(item.Mid, tree);
            }
            return await Task.FromResult(treelists);
        }
        public async Task Getchidren(int id, PublicTree<Menues> tree)
        {
            var list = await menues.GetvaluesByResult(x => x.Mpid == id && !x.IsDel);
            foreach (var item in list)
            {
                if (tree.children == null)
                {
                    tree.children = new List<PublicTree<Menues>>();
                }
                var substree = new PublicTree<Menues>
                {
                    label = item.Mname,
                    level = item.Mid,
                    pid=item.Mpid,
                    route = item.Mroute,
                    children = null
                };
                tree.children.Add(substree);
                await Getchidren(item.Mid, substree);
            }
        }
    }
}
